import db, { mysql } from 'src-ssr/db/connect';
import schedule from 'node-schedule';
import * as tools from 'src-ssr/util/common';
import { Sequelize, Op } from 'sequelize';
import models from 'src-ssr/db/sequelize';

/**
 * 清理操作日志
 * @param {number} tid 租户id
 */
async function clearLogs (tid = 0) {
  const logs = await tools.getSystemConfig('logs', tid);
  if (logs) {
    models.t_operation_logs.destroy({
      where: {
        create_time: {
          [Op.lt]: Date.now() / 1000 - logs.expireDays * 86400
        },
        tenant_id: tid
      }
    });
  }
  // mysql.query('delete from operation_logs where create_time<?', [Date.now() / 1000 - logs.expireDays * 86400]);
}

export const restart = async () => {
  if (global._schedule) {
    global._schedule.cancel();
    global._schedule = null;
  }
  // 每天凌晨 02：29：29执行
  global._schedule = schedule.scheduleJob('29 29 02 * * *', async () => {
    clearLogs();
  });
};

export default { restart };
